/*
 * @Author: jswang
 * @Date: 2021-07-25 23:05:15
 * @LastEditTime: 2021-07-29 10:09:47
 */
import axios from 'axios'
import store from '@/store'
import { Message } from 'element-ui'
import { getTimestamp } from './auth';
import router from '@/router'
const TimeOut = 3600 //定义超时时间
const service = axios.create({
    // 当执行 npm run dev  => .env.development=>/api  => 跨域代理
    baseURL: process.env.VUE_APP_BASE_API,
    timeout: 5000
});

service.interceptors.request.use(config => {
    // Do something before request is sent
    //token 失效的主动介入
    if (store.getters.token) {
        //只有在有token 的情况下,才有必要去检查时间戳是否超时
        if (isCheckTimeOut()) {
            //为true 表示 token 超过 1小时 过期了
            //token没用了,因为超时了
            store.dispatch('user/logout') //登出操作
                //跳转到登陆页面
            router.push('/login')
                //这里是一个Promise对象,token过期了,就得返回错误信息,并结束promise
            return Promise.reject(new Error("token过期了"))
        }
        //请求时,注入token
        config.headers.Authorization = 'Bearer' + ' ' + store.getters.token
    }
    //config 是我们的请求配置信息,必须返回的
    return config;
}, error => {
    // Do something with request error
    return Promise.reject(error);
});

service.interceptors.response.use(response => {
    // Do something before response is sent
    //axios 默认加了一层data
    const { success, message, data } = response.data
    if (!success) {
        //提示错误信息
        Message.error(message)
            //业务已经出错,不能then   要catch  错误
        return Promise.reject(new Error(message))
    }
    return data
}, error => {
    // Do something with response error
    //token失效的被动处理
    if (error.response && error.response.data && error.response.data.code === 10002) {
        //当等于 10002时,表示后端告诉我token过期了
        store.dispatch('user/logout')
        router.push('/login')
    } else {
        Message.error(error.message) //提示错误信息
    }
    return Promise.reject(error); //返回一个执行错误,让当前的执行链跳出成功,直接进入catch

});

//检查token时间是否过期
function isCheckTimeOut() {
    let currentTime = Date.now() //当前时间戳
    let timestamp = getTimestamp() //缓存中的时间戳
    return (currentTime - timestamp) / 1000 > TimeOut
}
export default service
// import { MessageBox, Message } from 'element-ui'
// import store from '@/store'
// import { getToken } from '@/utils/auth'

// // create an axios instance
// const service = axios.create({
//   baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
//   // withCredentials: true, // send cookies when cross-domain requests
//   timeout: 5000 // request timeout
// })

// // request interceptor
// service.interceptors.request.use(
//   config => {
//     // do something before request is sent

//     if (store.getters.token) {
//       // let each request carry token
//       // ['X-Token'] is a custom headers key
//       // please modify it according to the actual situation
//       config.headers['X-Token'] = getToken()
//     }
//     return config
//   },
//   error => {
//     // do something with request error
//     console.log(error) // for debug
//     return Promise.reject(error)
//   }
// )

// // response interceptor
// service.interceptors.response.use(
//   /**
//    * If you want to get http information such as headers or status
//    * Please return  response => response
//   */

//   /**
//    * Determine the request status by custom code
//    * Here is just an example
//    * You can also judge the status by HTTP Status Code
//    */
//   response => {
//     const res = response.data

//     // if the custom code is not 20000, it is judged as an error.
//     if (res.code !== 20000) {
//       Message({
//         message: res.message || 'Error',
//         type: 'error',
//         duration: 5 * 1000
//       })

//       // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
//       if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
//         // to re-login
//         MessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', {
//           confirmButtonText: 'Re-Login',
//           cancelButtonText: 'Cancel',
//           type: 'warning'
//         }).then(() => {
//           store.dispatch('user/resetToken').then(() => {
//             location.reload()
//           })
//         })
//       }
//       return Promise.reject(new Error(res.message || 'Error'))
//     } else {
//       return res
//     }
//   },
//   error => {
//     console.log('err' + error) // for debug
//     Message({
//       message: error.message,
//       type: 'error',
//       duration: 5 * 1000
//     })
//     return Promise.reject(error)
//   }
// )